<template>
  <n-select
    v-model:value="selectedModel"
    :options="selectOptions"
    :consistent-menu-width="false"
    :get-show="getShow"
    :on-update:value="handleSelectChange"
    class="footer-model-selector"
    placeholder="选择模型"
    size="small"
    :render-label="renderLabel"
  />
</template>

<script setup lang="ts">
import { computed, onMounted, watch, h } from 'vue'
import { NSelect, NIcon } from 'naive-ui'
import { ConstructOutline, EyeOutline, InfiniteOutline } from '@vicons/ionicons5'
import { useModelStore } from '../../shared/stores/model'

const modelStore = useModelStore()

// API前缀，从环境变量中获取
const apiPrefix = import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8080'

const props = defineProps({
  currentModel: { type: [String, Number], default: '' },
  direction: { type: String, default: 'top' }, // 弹窗展示方向，默认为'top'
  modelTag: { type: String, default: '对话' },  // 模型标签，默认为'对话'
  modelType: { type: String, default: '' }  // 模型类型，用于根据type字段过滤
})

const emit = defineEmits(['select-model'])

// 从store获取模型选项
const modelOptions = computed(() => modelStore.modelOptions)
const filteredModelOptions = computed(() => {
  // 如果指定了modelType，则使用type字段过滤
  if (props.modelType) {
    return modelStore.getModelsByType(props.modelType).map(model => ({
      label: model.name,
      value: model.id,
      icon: model.icon,
      tags: model.tags ? (typeof model.tags === 'string' ? model.tags.split(',').map(tag => tag.trim()).filter(tag => tag !== '') : model.tags) : []
    }))
  }
  
  // 否则使用原来的tags过滤方式
  if (!props.modelTag) return modelOptions.value
  return modelOptions.value.filter(option => 
    option.tags && option.tags.includes(props.modelTag)
  )
})

// 转换为n-select需要的选项格式
const selectOptions = computed(() => {
  return filteredModelOptions.value.map(option => ({
    label: option.label,
    value: Number(option.value),
    icon: option.icon,
    tags: option.tags
  }))
})

// 当前选中的模型
const selectedModel = computed({
  get: () => Number(props.currentModel) || null,
  set: (value) => {
    if (value !== Number(props.currentModel)) {
      emit('select-model', value)
    }
  }
})

// 自定义渲染选项标签
const renderLabel = (option: any) => {
  return h('div', { style: 'display: flex; align-items: center; justify-content: space-between;' }, [
    h('div', { style: 'display: flex; align-items: center; flex: 1; min-width: 0; margin-right: 8px;' }, [
      option.icon ? h('img', {
        src: `${apiPrefix}${option.icon}`,
        alt: 'icon',
        style: 'width: 18px; height: 18px; margin-right: 6px; flex-shrink: 0;'
      }) : null,
      h('span', {
        style: 'white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: block; font-size: 14px;'
      }, option.label)
    ]),
    h('div', { style: 'display: inline-flex; align-items: center; gap: 4px; flex-shrink: 0;' }, [
      option.tags && option.tags.includes('工具') ? h(NIcon, { size: 16, color: '#16baaa' }, { default: () => h(ConstructOutline) }) : null,
      option.tags && option.tags.includes('视觉') ? h(NIcon, { size: 16, color: '#16baaa' }, { default: () => h(EyeOutline) }) : null,
      option.tags && option.tags.includes('推理') ? h(NIcon, { size: 16, color: '#16baaa' }, { default: () => h(InfiniteOutline) }) : null
    ])
  ])
}

// 处理选择变化
const handleSelectChange = (value: number) => {
  // 确保modelId是number类型，与后端保持一致
  const modelIdNum = Number(value)
  modelStore.setModelByTag(props.modelTag, modelIdNum)
  
  // 如果是对话标签，同时更新currentChatModel和currentModelId
  if (props.modelTag === '对话') {
    modelStore.setCurrentChatModel(modelIdNum)
    modelStore.setCurrentModelId(modelIdNum)
  }
  
  // 更新当前模型的标签
  const selectedModel = modelOptions.value.find(opt => Number(opt.value) === modelIdNum)
  if (selectedModel && selectedModel.tags) {
    modelStore.setCurrentModelTags(selectedModel.tags)
  }
  
  // 发出select-model事件，通知父组件模型已选择
  emit('select-model', modelIdNum)
}

// 获取下拉菜单显示状态
const getShow = () => {
  return true
}

// 监听currentModel的变化，确保组件能正确响应外部传入的模型ID变化
watch(() => props.currentModel, (newModelId) => {
  if (newModelId && modelOptions.value.length > 0) {
    // 将newModelId转换为number以便比较
    const newModelIdNum = Number(newModelId)
    // 更新当前模型的标签
    const selectedModel = modelOptions.value.find(opt => Number(opt.value) === newModelIdNum)
    if (selectedModel && selectedModel.tags) {
      modelStore.setCurrentModelTags(selectedModel.tags)
    } else {
      modelStore.setCurrentModelTags([])
    }
  }
}, { immediate: true })

// 监听modelStore.currentChatModel的变化，确保组件能正确响应store中的模型变化
watch(() => modelStore.currentChatModel, (newModelId) => {
  // 如果props.currentModel为空或与新值不匹配，则更新props.currentModel
  if (newModelId && newModelId !== Number(props.currentModel)) {
    emit('select-model', newModelId)
  }
}, { immediate: true })

onMounted(async () => {
  // 从store加载模型列表
  try {
    console.log(`ModelSelector[${props.modelTag}]: 开始初始化`)
    // 加载模型列表
    console.log(`ModelSelector[${props.modelTag}]: 开始加载模型列表`)
    await modelStore.loadModels()
    console.log(`ModelSelector[${props.modelTag}]: 模型列表加载完成，共${modelStore.models.length}个模型`)
    
    // 获取过滤后的模型列表
    const filtered = filteredModelOptions.value
    console.log(`ModelSelector[${props.modelTag}]: 过滤后的模型列表`, filtered)
    
    if (filtered.length > 0) {
      // 确定当前应该使用的模型ID
      let currentModelId = props.currentModel
      
      // 如果props.currentModel为空，则尝试从store获取
      if (!currentModelId) {
        currentModelId = modelStore.currentChatModel
        console.log(`ModelSelector[${props.modelTag}]: 从store获取当前模型ID`, currentModelId)
      }
      
      // 如果仍然为空，则尝试从标签获取
      if (!currentModelId) {
        currentModelId = modelStore.getModelByTag(props.modelTag)
        console.log(`ModelSelector[${props.modelTag}]: 从标签获取当前模型ID`, currentModelId)
      }
      
      // 将currentModelId转换为number以便比较
      const currentModelIdNum = Number(currentModelId)
      
      // 检查当前模型ID是否存在于过滤后的列表中
      if (currentModelId && filtered.some(opt => Number(opt.value) === currentModelIdNum)) {
        console.log(`ModelSelector[${props.modelTag}]: 当前模型ID存在于列表中`, currentModelIdNum)
        // 如果当前模型ID与props.currentModel不同，则发出事件更新
        if (currentModelIdNum !== Number(props.currentModel)) {
          console.log(`ModelSelector[${props.modelTag}]: 发出select-model事件`, currentModelIdNum)
          emit('select-model', currentModelIdNum)
        }
      } else if (filtered.length > 0) {
        // 如果当前模型ID不在列表中，则使用第一个模型
        const firstModelId = Number(filtered[0].value)
        console.log(`ModelSelector[${props.modelTag}]: 使用第一个模型作为默认`, firstModelId)
        emit('select-model', firstModelId)
        
        // 保存第一个模型作为默认选择
        modelStore.setModelByTag(props.modelTag, firstModelId)
        
        // 如果是对话标签，同时更新currentChatModel
        if (props.modelTag === '对话') {
          modelStore.setCurrentChatModel(firstModelId)
        }
      }
      
      // 初始化时同步标签
      const finalModelId = Number(props.currentModel || modelStore.currentChatModel || filtered[0]?.value)
      if (finalModelId) {
        const found = modelOptions.value.find(opt => Number(opt.value) === finalModelId)
        if (found && found.tags) {
          modelStore.setCurrentModelTags(found.tags)
        } else {
          modelStore.setCurrentModelTags([])
        }
      }
    } else {
      console.warn(`ModelSelector[${props.modelTag}]: 没有找到匹配的模型`)
    }
  } catch (error) {
    console.error(`ModelSelector[${props.modelTag}]: 加载模型列表失败:`, error)
  }
})
</script>

<style scoped>
.footer-model-selector {
  min-width: 200px;
  max-width: 300px;
}

/* 自定义下拉选项样式 */
:deep(.n-base-selection) {
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
}

:deep(.n-base-selection:hover) {
  border-color: #16baaa;
  box-shadow: 0 2px 8px rgba(22, 186, 170, 0.15);
}

:deep(.n-base-selection .n-base-selection-label) {
  height: 32px;
  line-height: 32px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

:deep(.n-base-selection .n-base-selection-border) {
  border: none;
}

:deep(.n-base-selection .n-base-selection-arrow) {
  transition: transform 0.2s;
}

:deep(.n-base-selection:hover .n-base-selection-arrow) {
  transform: rotate(180deg);
}

/* 下拉菜单样式 */
:deep(.n-base-select-menu) {
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-height: 300px;
  overflow-y: auto;
}

:deep(.n-base-select-option) {
  padding: 8px 12px;
  border-bottom: 1px solid #f0f0f0;
  min-height: 36px;
}

:deep(.n-base-select-option:last-child) {
  border-bottom: none;
}

:deep(.n-base-select-option:hover) {
  background-color: #f5f5f5;
}

:deep(.n-base-select-option.n-base-select-option--selected) {
  background-color: #e8f5f8;
  color: #16baaa;
  font-weight: 500;
}

/* 自定义滚动条样式 */
:deep(.n-base-select-menu::-webkit-scrollbar) {
  width: 8px;
}

:deep(.n-base-select-menu::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(.n-base-select-menu::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
  border: 1px solid #f1f1f1;
}

:deep(.n-base-select-menu::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}
</style>